//
//  NewFeatureViewController.swift
//  WeiboDemo
//
//  Created by Quentin Zang on 2020/3/16.
//  Copyright © 2020 臧乾坤. All rights reserved.
//

import UIKit
import SnapKit

// 可重用 CellId
private let WBNewFeatureViewCellId = "WBNewFeatureViewCellId"

// 新特征图像的数量
private let WBNewFeatureImageCount = 4

class NewFeatureViewController: UICollectionViewController {

    // MARK: - 构造函数
    init() {
        // super.指定的构造函数
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = UIScreen.main.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .horizontal
        
        // 构造函数，完成之后内部属性才会被创建
        super.init(collectionViewLayout: layout)
        
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        collectionView.showsHorizontalScrollIndicator = false
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 隐藏状态栏
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(NewFeatureCell.self, forCellWithReuseIdentifier: WBNewFeatureViewCellId)

        // Do any additional setup after loading the view.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

//    override func numberOfSections(in collectionView: UICollectionView) -> Int {
//        // #warning Incomplete implementation, return the number of sections
//        return 0
//    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return WBNewFeatureImageCount
        
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WBNewFeatureViewCellId, for: indexPath) as! NewFeatureCell
    
        // Configure the cell
        //cell.backgroundColor = indexPath.item % 2 == 0 ? .red : .green
        
        cell.imageIndex = indexPath.item
    
        return cell
    }
    
    // scrollView 停止滚动方法
    override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 再最后一页才调用动画方法
        // 根据contentOffset 计算页数
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        // 判断是否是最后一页
        if page != WBNewFeatureImageCount - 1 {
            return
        }
        
        // cell 慢放动画
        let cell = collectionView.cellForItem(at: IndexPath(item: page, section: 0)) as! NewFeatureCell
        
        // 显示动画
        cell.showButtonAnim()
    }
    
}

// MARK: - 新特性 Cell
private class NewFeatureCell: UICollectionViewCell {
    
    // 图像属性
    var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            // 隐藏按钮
            startButton.isHidden = true
        }
    }
    
    @objc private func clickStartButton() {
        print("开始体验")
        // 发送通知
        let noti = NSNotification.Name(rawValue: WBSwitchRootViewControllerNotification)
        NotificationCenter.default.post(name: noti, object: nil)
    }
    
    /// 显示按钮动画
    func showButtonAnim() {
        
        startButton.isHidden = false
        startButton.transform = CGAffineTransform(scaleX: 0, y: 0)
        startButton.isUserInteractionEnabled = false
        UIView.animate(withDuration: 1.6,           // 动画时长
                       delay: 0,                    // 延时时间
                       usingSpringWithDamping: 0.6, // 弹力系数 0-1，越小越弹
                       initialSpringVelocity: 10,    // 初始速度，模拟重力加速度
                       options: [],                  // 动画选项
                       animations: {
            self.startButton.transform = .identity
        }) { (_) in
            // print("OK")
            self.startButton.isUserInteractionEnabled = true
        }
    }
    
    // frame 的大小是 layout.itemSize 指定的
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        // 1.添加控件
        addSubview(iconView)
        addSubview(startButton)
        // 2.指定位置
        iconView.frame = bounds
        
        startButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.snp.centerX)
            make.bottom.equalTo(self.snp.bottom).multipliedBy(0.7)
        }
        
        // 3.监听方法
        startButton.addTarget(self, action: #selector(clickStartButton), for: .touchUpInside)
    }
    
    // MARK: - 懒加载控件
    
    /// 图像
    private lazy var iconView: UIImageView = UIImageView()
    private lazy var startButton: UIButton = UIButton(title: "开始体验", color: .white, imageName: "new_feature_finish_button")
}
